<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>SocketIO客户端</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<!--    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>-->
    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js" ></script>
    <style>
        body {
            padding: 20px;
        }

        #console {
            height: 450px;
            overflow: auto;
        }

        .connect-msg {
            color: green;
        }
        .disconnect-msg {
            color: red;
        }
    </style>
</head>
<body>
<h1>客户端测试</h1>
<hr style="height: 1px;border: none; border-top: 1px solid black;" />

<div style="width: 700px; float: left;">
    <h3>建立连接</h3>
    <div style="border: 1px;">
        <label>socketIO服务端地址:</label>
        <input type="text" id="url" value="http://127.0.0.1:8091?userId=U10000" style="width: 500px;" />
        <br>
        <br>
        <button id="connect" style="width: 100px;">建立连接</button>
        <button id="disconnect" style="width: 100px;">断开连接</button>
    </div>


    <hr style="height: 1px; border: none; border-top: 1px solid black;" />

    <h3>SocketIO Client发送消息</h3>
    <div style="border: 1px;">
        <label for="socketEvent"></label><input type="text" id="socketEvent" value="getUserRooms" />
        <br><br>
        <textarea id="content" maxlength="1000" cols="40" rows="5" placeholder="请输入内容"></textarea>
        <button id="send" style="width: 100px;">发送消息</button>
    </div>
    <hr style="height: 1px; border: none; border-top: 1px solid black;" />
</div>

<div style="float: left; margin-left: 50px;">
    <h3>消息</h3>
    <button id="clean" style="width: 100px;">清理输出</button>
    <div id="console" class="well"></div>
</div>
</body>

<script type="text/javascript">
    var socket;
    var errorCount = 0;
    var isConnected = false;
    var maxError = 5;

    // 连接
    function connect(url) {
        socket = io.connect(url)

<!--        socket = io(url,{-->
<!--            query:{-->
<!--                userId:"U1234"-->
<!--            }-->
<!--        });-->
        //socket.nsp = "/socketIo" // 命名空间
        console.log(socket)

        // 监听本次连接回调函数
        socket.on('connect', function() {
            isConnected = true;
            console.log('连接成功')
            serverOutput('<span class="connect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>连接成功</span>');
            errorCount = 0;
        });

        // 监听消息
        socket.on('message', function(data) {
            output('<span class="connect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + data + '</span>');
            console.log(data)
        });

        // 连接断开
        socket.on('disconnect', function() {
            isConnected = false;
            serverOutput('<span class="disconnect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + '已下线' + '</span>');
            console.log('连接断开')
        });

        // 监听连接错误
        socket.on('connect_error', function(data) {
            isConnected = false;
            serverOutput('<span class="disconnect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + '连接错误' + data + '</span>');
            errorCount++;
            if(errorCount >= maxError) {
                socket.disconnect();
            }
        });

        // 监听连接错误
        socket.on('connect_timeout', function(data) {
            serverOutput('<span class="disconnect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + '连接超时' + data + '</span>');
            errorCount++;
            if(errorCount >= maxError) {
                socket.disconnect();
            }
        });


        // 监听连接错误
        socket.on('error', function(data) {
            serverOutput('<span class="disconnect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + '系统错误' + data + '</span>');
            errorCount++;
            if(errorCount >= maxError) {
                socket.disconnect();
            }
        });

        // 监听消息确认
        socket.on('ack', function(data) {
            console.log('ack:'+data)
            var str = '消息发送失败';
            if(data == 1) {
                str = '消息发送成功';
            }

            serverOutput('<span class="connect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>' + str + '</span>');
        });
    }

    function output(message) {
        var element = $("<div>" + message + "</div>")
        $('#console').prepend(element);
    }

    function serverOutput(message) {
        var element = $("<div>" + message + "</div>");
        $('#console').prepend(element);
    }

    $("#connect").click(function() {
        if(!isConnected) {
            var url = $("#url").val();
            console.log('url:'+url)
            connect(url);
        } else {
            serverOutput('<span class="disconnect-msg"><font color="blue">' + getNowTime() + '&nbsp;</font>连接已建立,不需要重复建立</span>')
        }
    })

    $('#disconnect').click(function() {
        if(isConnected) {
            socket.disconnect();
        }
    })

    $("#send").click(function() {
        // 自定义的事件名称
        var socketEvent = $("#socketEvent").val();
        var content = $("#content").val(); // 发送的内容
        console.log('socketEvent:'+socketEvent);
        console.log('content:'+content);
        socket.emit(socketEvent,content, function(data1,data2) {
            console.log("ack1:"+data1);
            console.log("ack2:"+data2);
        });
    })

    $("#clean").click(function() {
        $('#console').html("");
    })

    function getNowTime() {
        var date = new Date();
        var year = date.getFullYear();
        var mon = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var min = date.getMinutes();
        var sec = date.getSeconds();
        var ms = date.getMilliseconds();
        // var eleDate = document.getElementById('Date');
        var date = year + "/" + mon + "/" + day + " " + hour + ":" + min + ":" + sec + "." + ms;
        return date;
    }
</script>
</html>